<template>
  <div class="photo-detail">
    <Header />
    
    <div class="container" v-if="photo">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>作品详情</el-breadcrumb-item>
        <el-breadcrumb-item>{{ photo.title }}</el-breadcrumb-item>
      </el-breadcrumb>
      
      <div class="detail-content">
        <div class="photo-view">
          <img :src="photo.imgUrl" alt="作品图片" class="main-image">
          <div class="photo-meta">
            <h1>{{ photo.title }}</h1>
            <div class="author-info">
              <span>作者：{{ photo.author }}</span>
              <span>类型：{{ photo.type === 1 ? '手机摄影' : '相机摄影' }}</span>
              <span>发布时间：{{ formatTime(photo.createTime) }}</span>
            </div>
            <div class="photo-stats">
              <el-rate v-model="photo.score" disabled show-score text-color="#ff9900"></el-rate>
              <div>
                <span>{{ photo.voteCount }}人投票</span>
                <span>{{ photo.viewCount }}次浏览</span>
              </div>
            </div>
            <div class="description">
              <p>{{ photo.description }}</p>
            </div>
            
            <el-divider></el-divider>
            
            <!-- 投票区域 -->
            <div class="vote-section" v-if="isLogin">
              <h3>为这个作品投票</h3>
              <el-form :model="voteForm" ref="voteForm" :rules="voteRules">
                <el-form-item prop="score">
                  <el-rate v-model="voteForm.score" :max="10" show-score></el-rate>
                </el-form-item>
                <el-form-item prop="comment">
                  <el-input v-model="voteForm.comment" type="textarea" rows="3" placeholder="写下您的评价（选填）"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitVote" :loading="voteLoading">提交评分</el-button>
                </el-form-item>
              </el-form>
            </div>
            <div class="login-tip" v-else>
              <el-alert
                title="登录后才能进行投票和评论"
                type="info"
                show-icon>
              </el-alert>
              <router-link to="/login" class="login-link">
                <el-button type="text">去登录</el-button>
              </router-link>
            </div>
          </div>
        </div>
        
        <!-- 评论区域 -->
        <div class="comment-section">
          <h3>用户评论 ({{ comments.length }})</h3>
          
          <!-- 发表评论 -->
          <div class="comment-form" v-if="isLogin">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="写下您的评论..."
              v-model="commentForm.content">
            </el-input>
            <el-button type="primary" @click="submitComment" :loading="commentLoading">发表评论</el-button>
          </div>
          
          <!-- 评论列表 -->
          <div class="comment-list" v-if="comments.length > 0">
            <div class="comment-item" v-for="comment in comments" :key="comment.id">
              <div class="comment-avatar">
                <el-avatar :src="comment.avatar || defaultAvatar"></el-avatar>
              </div>
              <div class="comment-content">
                <div class="comment-header">
                  <span class="comment-name">{{ comment.nickname }}</span>
                  <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
                </div>
                <div class="comment-text">{{ comment.content }}</div>
                <div class="comment-actions">
                  <el-button type="text" icon="el-icon-thumb">点赞 {{ comment.likeCount }}</el-button>
                  <el-button type="text" icon="el-icon-chat-dot-round">回复</el-button>
                </div>
              </div>
            </div>
          </div>
          
          <div class="no-comment" v-else>
            <p>暂无评论，快来发表第一条评论吧！</p>
          </div>
        </div>
      </div>
    </div>
    
    <div class="loading" v-else>
      <el-skeleton :rows="10" animated />
    </div>
  </div>
</template>

<script>
import Header from '@/components/Header.vue'
import { mapGetters } from 'vuex'

export default {
  name: 'PhotoDetail',
  components: {
    Header
  },
  data() {
    return {
      photo: null,
      comments: [],
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      voteForm: {
        score: 0,
        comment: ''
      },
      voteRules: {
        score: [{ required: true, message: '请为作品评分', trigger: 'change' }]
      },
      commentForm: {
        content: ''
      },
      voteLoading: false,
      commentLoading: false
    }
  },
  computed: {
    ...mapGetters(['isLogin', 'userId', 'nickname'])
  },
  created() {
    this.fetchPhotoDetail()
    this.fetchComments()
  },
  methods: {
    async fetchPhotoDetail() {
      try {
        const id = this.$route.params.id
        const res = await this.$http.get(`/photos/${id}`)
        if (res.data.code === 1) {
          this.photo = res.data.data
        } else {
          this.$message.error('获取作品详情失败')
        }
      } catch (error) {
        console.error('获取作品详情失败', error)
        this.$message.error('获取作品详情失败')
      }
    },
    async fetchComments() {
      try {
        const photoId = this.$route.params.id
        const res = await this.$http.get(`/comments/photo/${photoId}`)
        if (res.data.code === 1) {
          this.comments = res.data.data
        }
      } catch (error) {
        console.error('获取评论失败', error)
      }
    },
    async submitVote() {
      if (!this.isLogin) {
        this.$message.warning('请先登录')
        return
      }
      
      this.$refs.voteForm.validate(async valid => {
        if (valid) {
          this.voteLoading = true
          try {
            const voteData = {
              photoId: this.photo.id,
              userId: this.userId,
              score: this.voteForm.score,
              comment: this.voteForm.comment
            }
            
            const res = await this.$http.post('/votes', voteData)
            if (res.data.code === 1) {
              this.$message.success('投票成功')
              // 刷新作品详情
              this.fetchPhotoDetail()
              // 重置表单
              this.voteForm.score = 0
              this.voteForm.comment = ''
            } else {
              this.$message.error(res.data.msg || '投票失败')
            }
          } catch (error) {
            console.error('投票请求失败', error)
            this.$message.error('投票失败，请稍后重试')
          } finally {
            this.voteLoading = false
          }
        }
      })
    },
    async submitComment() {
      if (!this.isLogin) {
        this.$message.warning('请先登录')
        return
      }
      
      if (!this.commentForm.content.trim()) {
        this.$message.warning('评论内容不能为空')
        return
      }
      
      this.commentLoading = true
      try {
        const commentData = {
          photoId: this.photo.id,
          userId: this.userId,
          nickname: this.nickname,
          content: this.commentForm.content
        }
        
        const res = await this.$http.post('/comments', commentData)
        if (res.data.code === 1) {
          this.$message.success('评论成功')
          // 刷新评论列表
          this.fetchComments()
          // 重置表单
          this.commentForm.content = ''
        } else {
          this.$message.error(res.data.msg || '评论失败')
        }
      } catch (error) {
        console.error('评论请求失败', error)
        this.$message.error('评论失败，请稍后重试')
      } finally {
        this.commentLoading = false
      }
    },
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
    }
  }
}
</script>

<style scoped>
.photo-detail {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.detail-content {
  margin-top: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.photo-view {
  display: flex;
  padding: 20px;
}

.main-image {
  width: 60%;
  height: auto;
  object-fit: contain;
  border-radius: 5px;
}

.photo-meta {
  flex: 1;
  padding: 0 20px;
}

.author-info {
  display: flex;
  flex-direction: column;
  margin: 10px 0;
  color: #666;
}

.author-info span {
  margin-bottom: 5px;
}

.photo-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0;
}

.description {
  margin-top: 20px;
  line-height: 1.6;
}

.vote-section, .comment-section {
  padding: 20px;
}

.comment-form {
  margin-bottom: 20px;
}

.comment-form .el-button {
  margin-top: 10px;
  float: right;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  display: flex;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.comment-avatar {
  margin-right: 15px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  margin-bottom: 5px;
}

.comment-name {
  font-weight: bold;
  margin-right: 10px;
}

.comment-time {
  color: #999;
  font-size: 12px;
}

.comment-text {
  line-height: 1.6;
  margin-bottom: 10px;
}

.comment-actions {
  color: #999;
}

.no-comment {
  text-align: center;
  color: #999;
  padding: 30px 0;
}

.login-tip {
  margin: 20px 0;
}

.login-link {
  margin-top: 10px;
  display: inline-block;
}

.loading {
  padding: 20px;
}
</style> 